<template>
  <div class="sdy-search">
    <SdyHeader title="啥都有" back>
      <template #title>
        <van-search v-model="searchText" shape="round" background="#c72418" placeholder="请输入搜索关键词" />
      </template>
      <template #right>
        <van-button @click='searchHandler' size="small" type="success">搜索</van-button>
      </template>
    </SdyHeader>

    <!-- 搜索相关的内容显示 -->
    <!-- 如果 searchText 没有文本的时候显示 -->
    <!-- <SdySearchHistory v-if="!searchText"></SdySearchHistory> -->
    <!-- 如果 searchText 有文本的时候显示 -->
    <!-- <SdySearchList v-else></SdySearchList> -->

    <!-- 当 searchText 为 true 的时候渲染 SdySearchList 组件 -->
    <!-- 当 searchText 为 false 的时候渲染 SdySearchHistory 组件 -->
    <component :is="searchText ? SdySearchList : SdySearchHistory"></component>
  </div>
</template>

<script setup lang="ts">
import SdySearchHistory from './components/SdySearchHistory.vue'
import SdySearchList from './components/SdySearchList.vue'
import { ref,watch ,provide} from 'vue'
import {useRouter, type Router} from 'vue-router'
import search from 'vant/lib/search'
//api接口
import {searchListApi} from '@/api/goods'

import  type{ MyHotItem} from '@/config/interface'

const $router: Router = useRouter()

// 准备一个数据, 和 文本框 交互
const searchText = ref<string>('')

const searchHandler = ()=>{
  const text = searchText.value.trim()
  //非空验证
  if(!text)return
  $router.push({ path:'/list', query:{ search:text}})
}

// 准备数据表示搜索列表
const searchList = ref<MyHotItem[]>([])

//监控速搜关键字变化
watch(searchText,async ()=>{
  if(!searchText.value.trim())return
  const res = await searchListApi(searchText.value.trim())
  searchList.value = res.data
})
provide('searchList',searchList)
</script>

<style scoped lang="scss"></style>
